#include "ClientSocket.h"

ClientSocket::ClientSocket(SOCKET socket)
{
	this->socketConnection = socket;
}

ClientSocket::ClientSocket()
{
}

ClientSocket::~ClientSocket()
{
}

void ClientSocket::doConnect(const std::string& serverHost, const std::string& serverPort)
{
	doClose();
	struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    int addressResult = getaddrinfo(serverHost.c_str(), serverPort.c_str(), &hints, &addInfoResult);
    if (addressResult != 0)
    {
		Log::getInstance()->error("[SOCKET] getaddrinfo() failed! ; (ErrorCode: " + Log::getInstance()->intToString(addressResult) + " )");
    }

	struct addrinfo* ptr;
	for (ptr = addInfoResult; ptr != NULL; ptr = ptr->ai_next)
    {
	    socketConnection = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
	    if (socketConnection == INVALID_SOCKET)
	    {
			Log::getInstance()->error("[SOCKET] socket() failed! ; (ErrorCode: " + Log::getInstance()->intToString(WSAGetLastError()) + " )");
			continue;
	    }
       if (connect(socketConnection, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR)
       {
    	   doClose();
    	   Log::getInstance()->error("[SOCKET] connect() failed! ; (ErrorCode: " + Log::getInstance()->intToString(WSAGetLastError()) + " )");
    	   continue;
        }
       break;  // Si llegamos aqui, estamos conectados
    }
	if (ptr == NULL)
	{
		doClose();
		std::string errMessage = "No se pudo conectar el socket.";
		Log::getInstance()->error("[SOCKET] " + errMessage);
		throw NetworkException(errMessage);
	}
}
